package com.tcu.user.controller;

import com.tcu.exception.SmartException;
import com.tcu.result.R;
import com.tcu.user.entity.Permission;
import com.tcu.user.entity.Role;
import com.tcu.user.mapper.PermissionMapper;
import com.tcu.user.service.IRoleService;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/role")
public class RoleController {
    /**
     * 需要有的功能有 增加，删除，修改，列表,批量删除
     */
    private IRoleService roleService;
    private PermissionMapper permissionMapper;

    @Autowired
    public void setPermissionMapper(PermissionMapper permissionMapper) {
        this.permissionMapper = permissionMapper;
    }

    @Autowired
    public void setRoleService(IRoleService roleService) {
        this.roleService = roleService;
    }

    @PostMapping("add")
    public R add(@RequestBody Role role){
        if(role.getId()!=null){
            throw new SmartException(20001,"id不为空，无法增加");
        }
        boolean save = roleService.save(role);
        return save?R.success():R.error();
    }
    @Delete("delete/{id}")
    public R delete(@PathVariable String id){
        boolean b = roleService.removeById(id);
        return b?R.success():R.error();
    }
    @PostMapping("deleteBatch")
    public R deleteBatch(@RequestBody List<String> ids){
        boolean b = roleService.removeByIds(ids);
        return b?R.success():R.error();
    }
    @PostMapping("update")
    public R update(@RequestBody Role role){
        if(role.getId()==null){
            throw new SmartException(20001,"id为null，无法更新");
        }
        boolean b = roleService.updateById(role);
        return b?R.success():R.error();
    }
    @GetMapping("findById/{id}")
    public R findById(@PathVariable String id){
        Role byId = roleService.getById(id);
        return R.success().data("role", byId);
    }
    @GetMapping("list")
    public R list(){
        List<Role> list = roleService.list();
        return R.success().data("list", list);
    }
    /**
     * 1，根据角色 来获取 权限
     * 2，可以为 角色 更新权限
     */

    @GetMapping("getPermissionsByRid/{roleId}")
    public R getPermissionsByRid(@PathVariable String roleId){
        Set<Permission> permissionsByRid = permissionMapper.getPermissionsByRid(roleId);
        return R.success().data("permissions", permissionsByRid);
    }

    @PostMapping("updatePermissionForRole/{roleId}")
    public R updatePermissionForRole(@PathVariable String roleId,@PathVariable List<String> permissionIds){
        boolean flag=roleService.updatePermissionForRole(roleId,permissionIds);
        return R.success();
    }


}
